package com.example.seckill.aspect;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * 限流 AOP
 */
@Slf4j
@Aspect
public class LimitAspect {

    //每秒只发出100个令牌，此处是单进程服务的限流，内部采用令牌捅算法实现
    private static RateLimiter rateLimiter = RateLimiter.create(100.0);

    //Service层切点  限流
    @Pointcut("@annotation(com.example.seckill.annotation.ServiceLimit)")
    public void serviceAspect() {

    }

    @Around("serviceAspect()")
    public  Object around(ProceedingJoinPoint joinPoint) {
        Boolean flag = rateLimiter.tryAcquire();
        Object obj = null;
        try {
            if(flag){
                obj = joinPoint.proceed();
            }
        } catch (Throwable e) {
            e.printStackTrace();
            log.error("{}", e);
        }
        return obj;
    }
}
